package com.athl.netty.netty.heart;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

/**
 * @author hl
 * @Data 2020/9/2
 */
public class NettyServer {
    private int port;

    public NettyServer(int port) {
        this.port = port;
    }

    // 编写run处理客户端请求
    public void run() {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(8);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) // 设置日志级别
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 提供空闲状态的处理器
                            //  long readerIdleTime, 表示多长时间未读,发送一个心跳检测,检测连接状态
                            //  long writerIdleTime, 表示多长时间未写,发送一个心跳检测,检测连接状态
                            //  long allIdleTime,   表示多长时间未写和读,发送一个心跳检测,检测连接状态
                            // 当IdleStateHandler触发后，就会传递给管道的下一个handler去处理，通过调用handler的 userEventTiggered在该方法中去处理
                            pipeline.addLast(new IdleStateHandler(3, 5, 7, TimeUnit.SECONDS));
                            pipeline.addLast("myIdleHandler", new NettyServerHandler());
                        }
                    });
            System.out.println("服务器启动了");
            ChannelFuture channelFuture = bootstrap.bind(port).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println("服务端出现了异常 e = " + e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new com.athl.netty.netty.chat.NettyServer(6666).run();
    }
}
